import express, { Application, Request, Response } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';

// Import routes
import systemRoutes from './routes/system';
import authRoutes from './routes/auth';
import fileRoutes from './routes/file'; // 新增
import questionRoutes from './routes/question'; // 新增问题路由

// Import MinIO initialization
import { initializeBucket } from './config/minio'; // 新增
// Import MongoDB initialization
import { mongodb } from './config/mongodb'; // 新增

const app: Application = express();
const PORT: number = parseInt(process.env.PORT || '3000', 10);

// Middleware
app.use(helmet()); // Security headers
app.use(cors()); // Enable CORS
app.use(morgan('combined')); // Logging
app.use(express.json({ limit: '50mb' })); // 增加限制
app.use(express.urlencoded({ extended: true, limit: '50mb' })); // 增加限制

// Routes
app.use('/auth', authRoutes);
app.use('/system', systemRoutes);

// file
app.use('/file', fileRoutes); // 新增文件路由

// question
app.use('/question', questionRoutes); // 新增问题路由

// 404 handler
app.use('*', (req: Request, res: Response) => {
  res.status(404).json({
    success: false,
    message: 'Route not found',
  });
});

// Initialize MinIO, MongoDB and start server
const startServer = async () => {
  try {
    await initializeBucket(); // 初始化MinIO存储桶
    await mongodb.connect(); // 初始化MongoDB连接
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
};

// 优雅关闭
process.on('SIGINT', async () => {
  console.log('Shutting down gracefully...');
  await mongodb.disconnect();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  console.log('Shutting down gracefully...');
  await mongodb.disconnect();
  process.exit(0);
});

startServer();

export default app;
